package ProxyManager;

##########################
#     OmnibusProxy       #
#    Krzysztof Ulman     #
# Politechnika Krakowska #
#      Kraków 2012       #
##########################

use strict;
use warnings;

use Database;
use ProxyDto;
use ProxyTester;
use Screen;

our $db;

#statusy proxy
our $STATE_OK = 'OK';
our $STATE_ERROR = 'ERROR';

#czy pobierac wszystkie czy tylko aktywne wyszukiwarki
our $SEARCHERS_ALL = 1;
our $SEARCHERS_ACTIVE = 0;

#lista proxy
#my @proxies;

#lista wyszukiwarek
#my @searchers

#konstruktor
sub new {
	shift;
	my $self = {};
	bless $self;
	
	if(!$db) {
		$db = Database->new();
	}
	
	my $searchersRef = $db->getSearchers($SEARCHERS_ALL);
	$self->{searchers} = $searchersRef;
	
	return $self;	
}

#testuj wszystkie proxy
sub testProxies {
	my $self = shift;
	
	private_getProxies($self);
	private_testAllProxies($self);
}

#pobiera wszystkie proxy z bazy
sub private_getProxies {
	my $self = shift;
	my @proxies;
	
#	$db->selectAllProxies();
#	$db->selectNotCheckedProxies();
	$db->selectGoodProxies();
	while((my $id, my $address, my $port, my $state, my $hidesRealIp, my $lastChecked, my $info) = $db->getRow()) {
		my $proxyDto = ProxyDto->new();
		$proxyDto->setId($id);
		$proxyDto->setAddress($address);
		$proxyDto->setPort($port);
		$proxyDto->setState($state);
		$proxyDto->setHidesRealIp($hidesRealIp);
		$proxyDto->setLastChecked($lastChecked);
		$proxyDto->setInfo($info);
		push(@proxies, $proxyDto);
	}
	
	$self->{proxies} = \@proxies;
}

#testuje po kolei
sub private_testAllProxies {
	my $self = shift;
	
	my $proxyTester = ProxyTester->new();
	my @proxies = @{$self->{proxies}};
	foreach my $proxy (@proxies) {
		$proxyTester->testProxy($proxy);
		$db->updateProxyState($proxy->getId(), $proxy->getState(), $proxy->getHidesRealIp());
		
		if($proxy->getState() eq $STATE_OK) {
			#skoro samo proxy dziala to testujemy czy puszczaja je wyszukiwarki
			private_testProxyWithSearchers($self, $proxy);
		}
	}
}

#testuje czy przed podane proxy mozna laczyc sie do wyszukiwarek z listy
sub private_testProxyWithSearchers {
	my $self = shift;
	my $proxyDto = shift;
	my @searchers = @{$self->{searchers}};
	
	my $proxyTester = ProxyTester->new();
	foreach my $searcherDto (@searchers) {
		my $state = $proxyTester->testProxyWithSearcher($proxyDto, $searcherDto);
		Screen->printAndLogInfo("Checking searcher " . $searcherDto->getName() . ": " . $state);
		$db->saveProxiesState($proxyDto, $searcherDto, $state);
	}
}

1;